﻿using UnityEngine;
using System.Collections;

[RequireComponent (typeof(CharacterController))]

public class PlayerController : MonoBehaviour
{
    // Handling
    public float rotationSpeed = 1080;
    public float walkSpeed = 5;
    public float runSpeed = 20;
    public float dashSpeed = 25;

    // System
    private Quaternion targetRotation;

    // Components
    public Weapon weapon;
    private CharacterController controller;
    private Camera cam;

    // Use this for initialization
    void Start ()
    {
        controller = GetComponent<CharacterController> ();
        cam = Camera.main;
    }
    
    // Update is called once per frame
    void Update ()
    {
        Control ();
                
        if (Input.GetButtonDown ("ShootL"))
        {
            weapon.ShootLaser ();
        }

        if (Input.GetButton ("ShootR"))
        {
            weapon.ShootRocket ();
        }

        //Using key G as in the word Grenade
        if (Input.GetButtonDown ("Grenade"))
        {  
            weapon.ThrowGrenade ();
        }

        if (Input.GetButton("Quit"))
        {
            Application.Quit();
        }
    }

    void Control()
    {
        Vector3 mousePos = Input.mousePosition;
        mousePos = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.transform.position.y - transform.position.y));
        targetRotation = Quaternion.LookRotation(mousePos - new Vector3(transform.position.x, 0, transform.position.z));
        transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetRotation.eulerAngles.y, rotationSpeed * Time.deltaTime);
        
        Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
        
        Vector3 motion = input;
        motion *= (Mathf.Abs(input.x) == 1 & Mathf.Abs(input.z) == 1)? .7f : 1;
        
        if ((Input.GetButton("Walk")))
        {
            motion *= walkSpeed;
        }
        
        else if ((Input.GetButton("Dash")))
        {
            motion *= dashSpeed;
        }
        
        else
        {
            motion *= runSpeed;
        }
        
        motion += Vector3.up * -8;
        
        controller.Move(motion * Time.deltaTime);
    }
}